<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller {
	public $uid = 0;    //用户id
	public $mobile = 0; //用户手机号码
	public $isLogin = false;	// 知否已经登录
	public $opt = '';	//站点设置

    protected function _initialize(){ 
		
		$this->opt = D('Options')->getOpts();
		$this->assign('opt',$this->opt);
		
		$bottom_menu = bottom_menu();
		$this->assign('bottom_menu',$bottom_menu);
   }  
	
	//登录
	public function login(){
	
		// 提交登录
		if(IS_AJAX){
			$mobile   = I('mobile','','strval,strip_tags,trim'); //手机号码
			$password = I('password','','strip_tags,trim'); //密码
			
			if(empty($mobile) || empty($password)){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'手机号码或者密码不能为空'));
			}
			if(!isMobile($mobile)){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'手机号码格式错误'));	
			}

			// 登录
			$judge = D('User')->memberLogin($mobile,md5($password));
			if ($judge === true)
			{
				
				//判断是否微信端打开
				$this->ajaxReturn(array('status'=>'1','msg'=>'登录成功','url'=>U('Home/Index/index')));
			}
			else
			{
				$this->ajaxReturn(array('status' => $judge['status'], 'msg' => $judge['msg']));
			}
		}	

		//$this->assign('allow_free_reg', $allow_free_reg);
		$this->display('login');
	}
	
	public function select_user(){
		$this->display();
	}

	public function new_user(){

		//用户注册协议内容
		$deal = htmlspecialchars_decode($this->opt['article_prompt']);

		//判断微信链接是否绑定了uid,绑定了不在跳到首页
		//$wx_info_id = session('wx_info_id');
		if(!empty($wx_info_id)){
			$user_uid = M('UserWxInfo')->where(array('id'=>$wx_info_id))->getField('uid');
			if(!empty($user_uid)){
				header('Location:'.U('Home/Index/index'));
			}
		}
		
		if(IS_AJAX){
			$mobile   = I('mobile','','strval,strip_tags,trim'); //手机号码
			$captcha = I('captcha','','trim');	// 短信验证码
			$user_model = D('User');

			if(empty($mobile)){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'手机号码不能为空'));
			}

			if(!isMobile($mobile)){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'手机号码格式错误'));	
			}

			$mobile_s = M('User')->where(array('mobile'=>$mobile))->getField('id');
			if($mobile_s){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'手机号码已存在'));	
			}

			if(empty($captcha)){
				//$this->ajaxReturn(array('status' => '-1', 'msg' => '验证码不能为空'));
			}

			if ($user_model->checkResetCaptcha($captcha,$mobile) == false) {
				//$this->ajaxReturn(array('status' => '-1', 'msg' => '验证码错误！'));
			}

			$wx_info_id = session('wx_info_id');
			$UserWxInfo = M('UserWxInfo')->field('nickname,avatar')->where(array('id'=>$wx_info_id))->find();
			$thumb = $UserWxInfo['avatar'];

			$option_value = M('Options')->where(array("option_name"=>"probation"))->find();

			//试用期限增加
			if(!empty($option_value)){
				$user_time = "+{$option_value['option_value']} day";
				$valid_time = strtotime($user_time,NOW_TIME);	
			}else{
				$valid_time = 0;
			}
			
			$data = array(
				'mobile' => $mobile,
				'level' => 0,
				'status' => 0,
				'username' => $UserWxInfo['nickname']?$UserWxInfo['nickname']:'',
				'thumb' => $thumb,
				'createtime' => NOW_TIME,
				'valid_time' => $valid_time,
			);

			$fans_id = M('User')->add($data);
			
			
			//用户表关联微信表
			M('UserWxInfo')->where(array('id'=>$wx_info_id))->save(array('uid'=>$fans_id));

			//查出新用户是否是有介绍人
			$pid = M('Parent')->where(array('user_wx_id'=>$wx_info_id,'uid'=>0))->getField('pid');
			
			//如果没有介绍人
			if(empty($pid)){
				if( $fans_id > 0 ){
					$this->ajaxReturn(array('status'=>1,'msg'=>'登记成功','url'=>U('Home/Index/index')));
				}
			}

			//如果是有介绍人进来
			if(!empty($pid)){
				
				
				$result_info = M('UserRelationship')->where('subordinate_user = %d',$pid)->find();
				if(!empty($result_info)){
					$count = $result_info['level'];
					$top_scort = $result_info['scort'];
					$scort = $top_scort.','.$fans_id;
					$count += 1; 
				}else{
					$count = 2;
					$scort = $pid.','.$fans_id;
				}
				$p_data = array(
					'user_id' => $pid,
					'subordinate_user' => $fans_id,
					'createtime' => NOW_TIME,
					'level'=>$count,
					'scort'=>$scort
				);
				
				//关联上下级
				$result = M('UserRelationship')->add($p_data);
				
				//更新临时记录表的信息，确保下次不会再查出这条数据
				M('Parent')->where(array('user_wx_id'=>$wx_info_id))->save(array('uid'=>$fans_id));
				
				//微信通知上级我加入了
				import('Vendor.Wechat.access');
				$wechat = new \WechatAccess();
				$wechat->sendwxmessagepeopledealers($fans_id,$pid);

				if( $fans_id > 0 && $result > 0 ){
					$this->ajaxReturn(array('status'=>1,'msg'=>'登记成功','url'=>U('Home/Index/index')));
				}
			} 
			
		}	
		$this->assign(array(
			'deal'=>$deal,
		));
		$this->display();
	}

	//注册
	public function register(){
		// 如果有登录
		if ($this->isLogin)
		{
			$this->redirect('Home/Index/index');
			// $this->error('您已经登录，3秒后将自动调整首页',U('Home/Index/index'));
		}
		
		//跳转链接
		$uid = I('uid');
		header('Location:'.U('Home/Index/index',array('register_id' => $uid),true,true));
	}

	// 重置密码
	public function reset_password()
	{
		if (IS_AJAX) {
			$mobile	= I('mobile');	// 手机号码
			$password = I('password');	// 新密码
			$captcha = I('captcha');	// 短信验证码

			// 空提交验证
			if(empty($mobile))
			{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '手机号码不能为空'));
			}
			if(empty($password))
			{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '新密码不能为空'));
			}
			if(empty($captcha))
			{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '验证码不能为空'));
			}

			// 手机号码有效验证
			if(!isMobile($mobile)){
				$this->ajaxReturn(array('status' => '-1', 'msg' => '手机号码格式错误'));
			}

			// 密码有效验证
			if (!is_password($password)) {
				$this->ajaxReturn(array('status' => '-1', 'msg' => '密码格式不符合'));
			}

			$user_model = D('User');
			
			// 验证码校验
			if ($user_model->checkResetCaptcha($captcha,$mobile)) {
			
				$data = array(
					'password' => md5($password)
				);

				$judge = $user_model->where(array('mobile' => $mobile))->save($data); 
				if($judge === false){
					$this->ajaxReturn(array('status' => '-1', 'msg' => '密码重置失败'));
				}
				else
				{
					$this->ajaxReturn(array('status' => '1', 'msg' => '密码重置成功'));
				}

			}else{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '验证码错误'));
			}
		}
		$none_menu = I('m_b');
		$this->assign('user_mobile',$this->uid && $this->mobile ? $this->mobile : '');
		$this->assign('none_menu',$none_menu);
		$this->display('reset_password');
	}

	//登记手机号码
	public function sendResetCheckMobile()
	{
		if (IS_AJAX) {
			$mobile = I('mobile');	// 手机号码

			if (empty($mobile))
			{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '手机号码不能为空'));
			}
			if(!isMobile($mobile)){
				$this->ajaxReturn(array('status' => '-1', 'msg' => '手机号码格式错误'));	
			}
			
			$mobile_s = M('User')->where(array('mobile'=>$mobile))->getField('id');
			if($mobile_s){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'您输入的号码已被注册'));	
			}

			// 创建验证码
			$rand_captcha = rand(1000,9999);
		
			$message = "您的操作验证码是：".$rand_captcha."。请不要把验证码泄露给其他人。";
			
			$sendsmstype = sendSMS($mobile,$message,true);
			
			//短信发送成功记录
			if($sendsmstype){
				M('SmsCode')->add(array('mobile'=>$mobile,'code'=>$rand_captcha,'createtime'=>NOW_TIME));
			}
			
			$this->ajaxReturn(array('status' => '1', 'msg' => '手机验证码已发送'));
		}
		else
		{
			$this->error('错误参数',U('Home/Index/index'));
		}
	}

	public function sendresetcaptcha()
	{
		if (IS_AJAX) {
			$mobile = I('mobile');	// 手机号码

			if (empty($mobile))
			{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '手机号码不能为空'));
			}
			if(!isMobile($mobile)){
				$this->ajaxReturn(array('status' => '-1', 'msg' => '手机号码格式错误'));	
			}
			
			$mobile_s = M('User')->where(array('mobile'=>$mobile))->getField('id');
			if(empty($mobile_s)){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'您输入的号码未注册'));	
			}

			// 创建验证码
			$rand_captcha = rand(1000,9999);
		
			$message = "您的操作验证码是：".$rand_captcha."。请不要把验证码泄露给其他人。";
			
			$sendsmstype = sendSMS($mobile,$message,true);
			
			//短信发送成功记录
			if($sendsmstype){
				M('SmsCode')->add(array('mobile'=>$mobile,'code'=>$rand_captcha,'createtime'=>NOW_TIME));
			}
			
			$this->ajaxReturn(array('status' => '1', 'msg' => '手机验证码已发送'));
		}
		else
		{
			$this->error('错误参数',U('Home/Index/index'));
		}
	}

	// 注销前台会员
	public function logout()
	{
		//注销状态会员
		M('User')->where('id = %d',session('home_uid'))->save(array('is_lock'=>1));
		session('home_uid',null);
		session('home_member_info',null);
		session('home_wx','true');
		cookie('home_mobile',null);
		cookie('home_passwd',null);
		session('[destroy]');
		// 直接跳转
		$this->redirect('Home/Login/login');
	}

	//代理中心
	public function popularize(){
		$this->display('popularize');
	}

	// 推广链接
	public function spread()
	{
		$uid = I('uid',0,'intval');
		$uid = $uid > 0 ? $uid : session('home_uid');
		$user_info = D('User')->getMemberInfoById($uid);
		if (empty($user_info))
		{
			$this->error('错误操作',U('Home/Index/index'));
		}

		//搜寻系统设置
		$setting_array = D('Customcode')->open_custom_setting();
		//获取当前类型
		$type          = $setting_array['type'];
		//返回html
		$html          = D('Customcode')->return_html($type);
		//如果当前会员选项是0的话，更新会员选项
		D('Customcode')->update_user_setting($uid,$type);
		//根据用户设置，返回对应url
		$return_array = D('Customcode')->return_different_code($uid);
		$code         = $return_array['code'];
		$code_img     = $return_array['code_img'];

		$this->assign(array(
			'user_info'=>$user_info,
			'qrcode_url'=>$code,
			'code_img'=>$code_img,
			'html'=>$html,
		));

		$this->display('spread');
	}

	//保存修改二维码
	public function change_code(){

		$uid = I('uid',0,'intval');
		$uid = $uid > 0 ? $uid : session('home_uid');
		$user_info = D('User')->getMemberInfoById($uid);
		if (empty($user_info)){
			$this->error('错误操作',U('Home/Index/index'));
		}
		
		//搜寻系统是否开启了自定义二维码设置，如果开启了，则可以进入
		$id  = M('Options')->where(array('option_name'=>'open_custom_code','option_value'=>1))->getField('id');
		if(empty($id)){
			$this->error('错误操作',U('Home/Index/index'));
		}
		
		//找寻是否修改了二维码样是
		$param = M('CustomCode')->where('uid = %d',$uid)->field('id,param')->find();
		if(!empty($param['param'])){
			$param_array   = unserialize($param['param']);
			
			//组装对应的样式
			$code_style    = 'left:'.$param_array['position_x'].'px;top:'.$param_array['position_y'].'px;width:'.$param_array['code_width_size'].'px;height:'.$param_array['code_height_size'].'px;position:absolute';
			$background_style = '<img src="/'.$param_array['background_img'].'" alt="背景图片" id="background_display" style="width: 100%;height:'.$param_array['background_height'].'px">';
			$button_left   = "left:".$param_array['button_left'];
			$param_array['background_img'] = '/'.$param_array['background_img'];
		}else{
			
			$code_style      = 'width:100px;height:100px;position:absolute';

		}

		$this->assign(array(
			'upload_url'=>U("Home/Index/upload_picture"),//上传地址
			'param'=>$param_array,    //修改模板参数
			'qrcode_url'=>$code,
			'background_style'=>$background_style,//背景样是
			'code_style'=>$code_style,           //二维码样式
			'code_id'=>$param['id'],            //当前样是id
			'button_left'=>$button_left         //按钮距离左边多少像素
		));
		$this->display('change_code');
	}

	//异步保存修改二维码信息
	public function ajax_change_code(){
		if(IS_AJAX){
			$uid = $uid > 0 ? $uid : session('home_uid');
			$background_img = I('background_img','');
			$position_x     = I('position_x',0,'intval');
			$position_y     = I('position_y',0,'intval');
			$id             = I('code_id',0,'intval'); //模板id
			$code_width_size  = I('code_width_size',0);//二维码宽度
			$code_height_size = I('code_height_size',0);//二维码高度
			$background_width = I('background_width',0); //背景宽度
			$background_height= I('background_height',0);//背景高度
			$button_left      = I('button_left',0); //按钮往左


			//背景图片
			if(empty($background_img) && mb_strlen($background_img) <= 1){

				$this->error('请上传背景图片');
			}
			//截取不要第一个/号
			$background_img = substr($background_img,1);

			$data = array(
				'background_img'=>$background_img,
				'position_x'=>$position_x,
				'position_y'=>$position_y,
				'code_width_size'=>$code_width_size,       //二维码大小宽度
				'code_height_size'=>$code_height_size,       //二维码大小高度
				'background_width'=>$background_width,       //背景宽度
				'background_height'=>$background_height,     //背景高度
				'button_left'=>$button_left,                  //按钮左像素
			);

			//序列化保存数据
			$array  = serialize($data);

			if(!empty($id)) {

				$return_id = M('CustomCode')->where('id = %d',$id)->save(array('param'=>$array));

			}else{

				$add_array['param'] = $array;
				$add_array['uid'] = $uid;
				$add_array['createtime'] = NOW_TIME;

				$return_id = M('CustomCode')->add($add_array);

			}

			$data['uid'] = $uid;
			//成功后
			if($return_id !== false) {
				//获取合成图片
				Vendor('Wechat.paramCode');

				$savedir = "Uploads/paramcode/compound/";
				$savename = "compound_".$uid.".jpg";
				createParamCodeCard($savedir, $savename, $data);
				//使用了自定义二维码
				M('User')->where('id = %d',$uid)->save(array('use_custom_code'=>1,'use_system_code'=>0));
				$this->success('数据保存成功',U('Home/Login/spread/'));
			}else{
				$this->error('数据保存失败');
			}
		}
	}

	//使用系统二维码
	public function ajax_use_system_code(){
		if(IS_AJAX){
			$uid = $uid > 0 ? $uid : session('home_uid');
			$result_id = M('User')->where('id = %d and use_system_code = 0',$uid)->save(array('use_system_code'=>1,'use_custom_code'=>0));
			if($result_id !== false){
				D('Customcode')->compound_picture($uid);
				//使用了自定义二维码
				M('User')->where('id = %d',$uid)->save(array('use_custom_code'=>0,'use_system_code'=>1));
				
				$this->success('数据保存成功',U('Home/Login/spread/'));
			}else{
				$this->error('更新失败');
			}
		}
	}
	
	//展示二维码
	public function show_code(){
		$url = I('url','','base64_decode');//链接
		if(!empty($url)){
			import('Vendor.phpqrcode.phpqrcode');
			\QRcode::png($url, false,  'L',6,2);
		}
	}

	// 推广二维码
	public function qrcodeImg()
	{
		$user_model = D('User');

		$uid = I('uid',0,'intval');
		$uid = $uid > 0 ? $uid : session('home_uid');
		$user_info = $user_model->getMemberInfoById($uid);
	
		if (empty($user_info))
		{
			$this->error('错误操作',U('Home/Index/index'));
		}
		
		import('Vendor.phpqrcode.phpqrcode');
        $url    = $user_model->getMemberSpreadUrl($uid);
		\QRcode::png($url, false,  'L',6,2);
		
		
	}
	
}